package com.adingxiong.cft.config;


import com.adingxiong.cft.constant.JobConstant;
import com.adingxiong.cft.controller.quartz.TimeJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @ClassName InitQuarz
 * @Description TODO
 * @Author   初始化调度任务
 * @Date 2021/3/26 11:18
 **/
@Slf4j
@Configuration
public class InitQuartz {


    @Autowired
    private Scheduler scheduler;


    public void startJob() throws SchedulerException {
        initStartJob();
        scheduler.start();
    }

    private void initStartJob() {
        try {
            startTimeJob();
        } catch (Exception e) {
            log.info("初始化调度任务失败：{}",e.getMessage());
        } finally {

        }
    }

    private void startTimeJob() {
        try {
            List<String> jobGroupNames = scheduler.getJobGroupNames();
            if(jobGroupNames != null && !jobGroupNames.contains(JobConstant.HOLIDAY_GROUP)){
                createScheduleJob(JobConstant.HODIDAY_JOBTETAIL,JobConstant.HOLIDAY_GROUP,JobConstant.HOLIDAY_TIGGER ,"0 * 23 * * ? ",TimeJob.class);
                log.info("创建 startTimeJob 任务成功");
            } else {
                log.info("已经存在 startTimeJob 任务");
            }
            scheduler.resumeTriggers(GroupMatcher.groupEquals(JobConstant.HOLIDAY_GROUP));
        } catch (SchedulerException e) {
            log.error("创建时间任务失败:{}",e.getMessage());
        }

    }

    /**
     * 创建定时任务工具类
     * @param jobDetail
     * @param group
     * @param jobTrigger
     * @param icon
     * @param jobClass
     * @throws SchedulerException
     */
    private void createScheduleJob(String jobDetail, String group, String jobTrigger, String icon, Class<? extends Job> jobClass) throws SchedulerException {
        JobDetail detail = JobBuilder.newJob(jobClass)
                .withIdentity(jobDetail,group)
                .build();

        CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule(icon);
        // 如果错过则不执行 等待下次执行
        builder.withMisfireHandlingInstructionDoNothing();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .startNow()
                .withIdentity(jobTrigger,group)
                .withSchedule(builder)
                .build();

        scheduler.scheduleJob(detail,trigger);
    }

}
